
//自动注册路由

import { RouteRecordRaw } from "vue-router";
import { env } from "../../types/helper";

//找到布局组件
const layouts =import.meta.globEager("../layouts/*") //vite的api方法
//找到子路由
const views =import.meta.globEager("../views/**/*")



function getRoutes(){

    const layoutRoutes =[] as RouteRecordRaw[] 
    //遍历组件
Object.entries(layouts).forEach(([file,module]) =>{
    // console.log(file);
    const route = getRouteByModule(file,module);

    //子路由
    route.children=getChildRoutes(route)

    //每次创建一个路由就push进去
    layoutRoutes.push(route)
})


return layoutRoutes;
}


//获取布局的子路由
function getChildRoutes(layoutRoute:RouteRecordRaw){

 //遍历子路由
const routes =[] as RouteRecordRaw []
 Object.entries(views).forEach(([file,module])=>{
   
    
     if(file.includes(`../views/${layoutRoute.name as string}`)){
        
       const route =getRouteByModule(file,module)
       routes.push(route)
       
     }
 })
 
 return routes;
}

//返回布局路由对象
function getRouteByModule(file:string, module:any){ 
  
   const  name =file.replace(/.+layouts\/|.+views\/|\.vue/gi, '')  //替换子路由或者父路由都可以调用
       //定义路由对象
 
        const route ={
            name:name.replace("/","."),
            path:`/${name}`,
            component:module.default
        } as RouteRecordRaw 

      
 return Object.assign(route,module.default?.route) //看每个组件里面是否有route导出(是否需要验证的) module.default?.route
}

export default   getRoutes